package net.neiquan.neiquandemowithkf.fragment;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import net.neiquan.neiquandemowithkf.R;
import net.neiquan.neiquandemowithkf.activity.ContainerActivity;
import net.neiquan.neiquandemowithkf.activity.MainActivity;
import net.neiquan.neiquandemowithkf.api.NetUtils;
import net.neiquan.neiquandemowithkf.application.MyApplication;
import net.neiquan.neiquandemowithkf.entity.Captcha;
import net.neiquan.neiquandemowithkf.entity.User;
import net.neiquan.neiquandemowithkf.entity.UserModel;
import net.neiquan.neiquandemowithkf.inter.AppConstant;
import net.neiquan.neiquandemowithkf.utils.ResourcesUtils;
import net.neiquan.neiquandemowithkf.utils.Tools;
import net.neiquanlib.base.AppBaseFragment;
import net.neiquanlib.http.NetCallBack;
import net.neiquanlib.http.ResultModel;
import net.neiquanlib.inter.UserEvent;
import net.neiquanlib.widget.CustomCheckBox;

import org.greenrobot.eventbus.EventBus;
import org.haitao.common.utils.ToastUtil;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 作者 ： hjb
 * 时间 ： 2016/7/20.
 */

public class RegisterFragment extends AppBaseFragment {

    @InjectView(R.id.phone_et)
    EditText mPhoneEt;
    @InjectView(R.id.code_et)
    EditText mCodeEt;
    @InjectView(R.id.send_code_btn)
    Button mSendCodeBtn;
    @InjectView(R.id.new_psw_et)
    EditText mNewPswEt;
    @InjectView(R.id.confirm_psw_et)
    EditText mConfirmPswEt;
    @InjectView(R.id.complete_register_btn)
    Button mCompleteRegisterBtn;
    @InjectView(R.id.protocol_ckb)
    CustomCheckBox mProtocolCkb;
    @InjectView(R.id.protocol_ll)
    LinearLayout mProtocolLl;
    boolean isRegister = true;
    private String phone;
    private String code;
    private String newPsw;
    private boolean isSend = false;
    private CountDownTimer mTimer;// 倒计时；
    private String captchaCode;

    @Override
    public View initRootView() {
        rootView = mInflater.inflate(R.layout.fragment_register, null);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void setViews() {
        setBackGone();
        isRegister = getArguments().getBoolean(AppConstant.REGISTER, true);
        setTitleTv(isRegister ? "注册" : "找回密码");
        if (!isRegister) {
            mProtocolLl.setVisibility(View.GONE);
            mCompleteRegisterBtn.setText("找回密码");
        }
    }


    @Override
    public void initData() {
        if (isRegister) {
            setButtonBackground(mProtocolCkb.isChecked());
        }
        mProtocolCkb.setOnCheckedChangeListener(new CustomCheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CustomCheckBox checkBox, boolean isChecked) {
                setButtonBackground(isChecked);
            }
        });
    }

    /**
     * 设置注册按钮是否可点击
     *
     * @param isChecked
     */
    private void setButtonBackground(boolean isChecked) {
        if (!isChecked) {
            mCompleteRegisterBtn.setClickable(false);
            mCompleteRegisterBtn.setBackgroundColor(ResourcesUtils.getColor(R.color.gray));
        } else {
            mCompleteRegisterBtn.setClickable(true);
            mCompleteRegisterBtn.setBackgroundResource(R.drawable.button_bule);
        }
    }


    @OnClick({R.id.send_code_btn, R.id.complete_register_btn, R.id.protocol_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_code_btn://发送验证码
                if (TextUtils.isEmpty(mPhoneEt.getText().toString().trim())) {
                    Toast.makeText(getActivity(), "请输入手机号", Toast.LENGTH_SHORT).show();
                } else {
                    sendCode(mPhoneEt.getText().toString().trim());
                }
                break;
            case R.id.complete_register_btn://完成注册
                checkComplete();
                break;
            case R.id.protocol_tv://用户协议
                ContainerActivity.startActivity(getActivity(), ProtocolFragment.class, null);
                break;
        }
    }

    private void sendCode(String phone) {
        if (isSend) {
            Toast.makeText(getActivity(), "验证码已发送", Toast.LENGTH_SHORT).show();
            return;
        }
        isSend = true;
        NetUtils.getInstance().getCaptcha(phone, new NetCallBack() {
            @Override
            public void onSuccess(String message, int errorCode, String response, ResultModel model) {
                mSendCodeBtn.setClickable(false);
                Captcha captcha = model.getModel();
                captchaCode = captcha.getCode();
                startTimer();
            }

            @Override
            public void onFail(String message, int errorCode, boolean dataError) {
                isSend = false;
                if (message != null) {
                    Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                }
            }
        }, Captcha.class);
    }

    private void startTimer() {
        mTimer = new CountDownTimer(60000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mSendCodeBtn.setText(millisUntilFinished / 1000 + "秒后重发");
            }

            @Override
            public void onFinish() {
                isSend = false;
                mSendCodeBtn.setText("获取验证码");
                mSendCodeBtn.setClickable(true);
            }
        };
        mTimer.start();
    }

    private void checkComplete() {
        phone = mPhoneEt.getText().toString().trim();
        code = mCodeEt.getText().toString().trim();
        newPsw = mNewPswEt.getText().toString().trim();
        String confirmPsw = mConfirmPswEt.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(getActivity(), "请输入手机号", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(code)) {
            Toast.makeText(getActivity(), "请输入验证码", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(captchaCode) || !code.equals(captchaCode)) {
            ToastUtil.shortShowToast("验证码不正确");
        } else if (TextUtils.isEmpty(newPsw)) {
            Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(confirmPsw)) {
            Toast.makeText(getActivity(), "请输入确认密码", Toast.LENGTH_SHORT).show();
        } else if (!confirmPsw.equals(newPsw)) {
            Toast.makeText(getActivity(), "两次密码输入不一致", Toast.LENGTH_SHORT).show();
        } else {
            Tools.showDialog(getActivity());
            if (isRegister) {
                register();
            } else {
                findPsw();
            }
        }
    }

    private void findPsw() {
        NetUtils.getInstance().passwordFind(phone,
                code, newPsw, new NetCallBack() {
                    @Override
                    public void onSuccess(String message, int errorCode, String response, ResultModel model) {
                        Tools.dismissWaitDialog();
                        UserModel userModel = model.getModel();
                        User user = userModel.getUser();
                        user.setUserToken(userModel.getUserToken());
                        MyApplication.getInstance().saveUser(user);
                        Intent intent = new Intent(getActivity(), MainActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                        EventBus.getDefault().post(new UserEvent(UserEvent.UPDATE_INFO));
                    }

                    @Override
                    public void onFail(String message, int errorCode, boolean dataError) {
                        Tools.dismissWaitDialog();
                        if (!TextUtils.isEmpty(message)) {
                            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                        }
                    }
                }, UserModel.class);
    }

    /**
     * 注册
     */
    private void register() {
        NetUtils.getInstance().register(phone, code, newPsw, new NetCallBack() {
            @Override
            public void onSuccess(String message, int errorcode, String response, ResultModel model) {
                Tools.dismissWaitDialog();
                UserModel userModel = model.getModel();
                User user = userModel.getUser();
                user.setUserToken(userModel.getUserToken());
                MyApplication.getInstance().saveUser(user);
                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                getActivity().finish();
                EventBus.getDefault().post(new UserEvent(UserEvent.UPDATE_INFO));
            }

            @Override
            public void onFail(String message, int errorCode, boolean dataError) {
                Tools.dismissWaitDialog();
                if (!TextUtils.isEmpty(message)) {
                    Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                }
            }
        }, UserModel.class);
    }

}
